#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Wed Jul 10 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
import datetime
import os
import pathlib
import urllib.request

from .. import config, utils
from .base import BaseHandler


class EDHandler(BaseHandler):

    def __init__(self, *args, **kwargs):
        self.alarm_info = {}
        return super().__init__(*args, **kwargs)

    def handle(self, msg):
        """
        获得详情数据类型
        :param msg:
        :return:
        """
        if self.alarm_info and self.alarm_info['uuid'] == msg['uuid']:
            self.alarm_info.update(msg)
            device_id = msg['deviceId']
            vehicle_id = self.not_exist_add_vehicle(device_id)
            # 判断报警是类型(图片or视频)
            if msg['edtype'] == '2':
                media_uri_category = 1
            elif msg['edtype'] == '3':
                media_uri_category = 2
            else:
                self.logger.warning(msg)
                return
            gps_time = self.timespan2str(msg['time'])
            data = {
                "category": utils.type_to_jt808(self.alarm_info),
                "start_time": gps_time,
                "end_time": gps_time,
                'vehicle_id': vehicle_id,
                "media_uri_category": media_uri_category,
                "media_uri": self.get_media_uri(self.alarm_info),
                "location": {
                    "latitude": float(self.alarm_info['lat']),
                    "longitude": float(self.alarm_info['lon']),
                    "speed": self.transform_speed(self.alarm_info['speed']),
                    "gps_time": gps_time,
                    "altitude": float(self.alarm_info['altitude']),
                    "direction": self.alarm_info['heading'],
                }
            }
            res = self.yb_api.send_alarm(data)
            self.alarm_info = {}
        else:
            self.alarm_info = msg

    def get_media_uri(self, msg):
        """
        对加密url进行解密
        :param msg:
        :return:
        """
        # 对图片和视频url进行筛选
        for k in ['front_img', 'back_img', 'front_video', 'back_video']:
            if k in msg and msg[k] != 'null':
                return self.download(msg['endpoint'], msg[k])

    def download(self, endpoint, file_path):
        url = self.ky_api.media_info(endpoint, file_path)
        new_file_path = self.make_new_path(file_path)
        urllib.request.urlretrieve(url, new_file_path)
        return new_file_path

    def make_new_path(self, file_path):
        filename = os.path.basename(file_path)
        day = datetime.date.today().strftime('%Y%m%d')
        if filename.endswith('.mp4'):
            p = os.path.join(self.MEDIA_UPLOADS_PATH, f'{day}/videos/')
        else:
            p = os.path.join(self.MEDIA_UPLOADS_PATH, f'{day}/images/')
        pathlib.Path(p).mkdir(parents=True, exist_ok=True)
        return f'uploads/{day}/images/{filename}'
